package com.example.demo.common.utils;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.SystemUtils;
import org.jetbrains.annotations.TestOnly;

import java.net.Inet4Address;
import java.net.UnknownHostException;
import java.util.Random;

/**
 * uuid生成工具类
 */
public class IdUtils {



	private static Snowflake snowflake = IdUtil.getSnowflake(getWorkId(),getDataCenterId());

	/**
	 * 生成long 类型的ID
	 * @return
	 */
	public static Long getId() {

		return snowflake.nextId();
	}

	/**
	 * 生成String 类型的ID
	 * @return
	 */
	public static String getIdStr() {
		return snowflake.nextIdStr();
	}

	/**
	 * workId使用IP生成
	 * @return workId
	 */
	private static Long getWorkId() {
		try {
			String hostAddress = Inet4Address.getLocalHost().getHostAddress();
			int[] ints = StringUtils.toCodePoints(hostAddress);
			int sums = 0;
			for (int b : ints) {
				sums = sums + b;
			}
			return (long) (sums % 32);
		}
		catch (UnknownHostException e) {
			// 失败就随机
			return RandomUtils.nextLong(0, 31);
		}
	}

	/**
	 * dataCenterId使用hostName生成
	 * @return dataCenterId
	 */
	private static Long getDataCenterId() {
		try {
			String hostName = SystemUtils.getHostName();
			int[] ints = StringUtils.toCodePoints(hostName);
			int sums = 0;
			for (int i: ints) {
				sums = sums + i;
			}
			return (long) (sums % 32);
		}
		catch (Exception e) {
			// 失败就随机
			return RandomUtils.nextLong(0, 31);
		}
	}

	/**
	 * 生成随机字符串
	 * @param length
	 * @return
	 */
	public static String getRandomString(int length){
		//区间
		String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		Random random=new Random();
		StringBuffer sb=new StringBuffer();
		for(int i=0;i<length;i++){
			int number=random.nextInt(62);
			sb.append(str.charAt(number));
		}
		return sb.toString();
	}



}
